﻿using Net_SCADA.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Net_SCADA
{
    public partial class Form_Run : fdBaseForm
    {
        Dictionary<string,Panel> groupPnl=new Dictionary<string, Panel>();
        private bool isFormLoading=true;
        private bool isCurrentPara=false;
        List<Label> proEdit=new List<Label>();
        Dictionary<string,Label> ProgramLabel=new Dictionary<string, Label>();//使用zoneID来绑定infoedit的textbox
        string SelectedProductVersion="";
        private bool isTmpModify=false;
        int designCols=10;
        int w;
        StringBuilder OldSetValues=new StringBuilder();
        //public List<Label> lstlbl = new List<Label>();
        private Font[] groupTitleFont = new Font[] { new Font("Microsoft YaHei", 12f), new Font("Arial", 12f) };
        private Font[] itemTitleFont = new Font[] { new Font("Microsoft YaHei", 9f), new Font("Arial", 9f) };
        private Font[] gridTitleFont = new Font[] { new Font("Microsoft YaHei", 12f), new Font("Arial", 12f)};
        private Font editBoxFont = new Font("Arial", 15f, FontStyle.Bold);
        Label lblModify =null;
        private Dictionary<string, string[]> gridTitle = new Dictionary<string, string[]>();

        public Form_Run()
        {
            InitializeComponent();
            designCols = NetLine.DesignCols;
        }

        private void Form_Run_Load(object sender , EventArgs e)
        {
            formLanguageIndex = -1;
            isFormLoading = true;
            designCols = NetLine.DesignCols;
            netForms.SetPostionAndSize(this);
            w = (this.Width - designCols * 5 - 5) / designCols;
            isTmpModify = false;
            LoadInterface();
            SetProductInfoGrid();
            LoadProgramEditInterface();
            LoadBatchInfos();
            isFormLoading = false;
        }
        private void Form_Run_Activated(object sender , EventArgs e)
        {
            btn_RunConfirm.Visible = !NetLine.isBatchStart;
            btn_BatchStop.Visible = NetLine.isBatchStart;
            btn_TmpModify.Visible = !isTmpModify;
            btnModifyConfirm.Visible = isTmpModify;
            if (formLanguageIndex != MultipleLanguage.systemLanguageIndex)
            {
                formLanguageIndex = MultipleLanguage.systemLanguageIndex;
                //foreach (Label lbl in lstlbl)
                //{
                //    if (lbl.Tag != null)
                //    {
                //        string[] s = lbl.Tag as string[];
                //        lbl.Text = s[formLanguageIndex];
                //    }
                //}
            }
        }


        private void LoadInterface()
        {
            pnl_Product.Location=pnl_BatchList.Location = new Point(2 , 34);
            pnl_Product.Size = pnl_BatchList.Size = new Size(this.Width - 4 , 213);
            grdBatchList.Location = grdProduct.Location = new Point(0 , 0);
            grdProduct.Size=grdBatchList.Size = new Size(pnl_BatchList.Width - netForms.fmTop.btnWidth - 2 , pnl_BatchList.Height);

            btnModifyConfirm.Size = btn_BatchStop.Size= btn_BatchConfirm.Size=btn_BatchCancel.Size= btn_ShowCurrentPara.Size= btn_RunConfirm.Size = btn_TmpModify.Size  = new Size(netForms.fmTop.btnWidth , netForms.fmTop.btnHeight);
            btnModifyConfirm.Font = btn_BatchStop.Font= btn_BatchConfirm.Font=btn_BatchCancel.Font= btn_ShowCurrentPara.Font= btn_RunConfirm.Font = btn_TmpModify.Font = fdPublicFunction.Getfont(btn_RunConfirm.Height / 3 , "宋体" , FontStyle.Regular);

            btn_BatchStop.Location= btn_BatchConfirm.Location= btn_RunConfirm.Location = new Point(pnl_BatchList.Width - btn_RunConfirm.Width , pnl_BatchList.Height - btn_RunConfirm.Height);
            btnModifyConfirm.Location = btn_BatchCancel.Location= btn_TmpModify.Location = new Point(btn_RunConfirm.Left , btn_RunConfirm.Top - 2 - btn_TmpModify.Height);
            btn_ShowCurrentPara.Location = new Point(btn_RunConfirm.Left , btn_TmpModify.Top - 2 - btn_ShowCurrentPara.Height);
            lbl_Search.Location = new Point(btn_RunConfirm.Left , 10);
            txt_SearchByName.Location = new Point(btn_RunConfirm.Left , lbl_Search.Height + 11);
            
            txt_SearchByName.Width = btn_RunConfirm.Width;
            lbl_ProgramTitle.Location = new Point(0 , pnl_BatchList.Top + pnl_BatchList.Height + 5);
            lbl_ProgramTitle.Width = this.Width;
            lbl_ModifyTitle.Font = new Font("Arial", 9f , FontStyle.Regular);
            txt_ModifyEdit.Font = new Font("Arial", 15f , FontStyle.Bold);
            txt_ModifyEdit.Width = w - 82;
            pnl_Modify.Size = new Size(w , 60);
            btn_ModifyConfirm.Size = new Size(80 , txt_ModifyEdit.Height);
            btn_ModifyConfirm.Location = new Point(pnl_Modify.Width - 80 , txt_ModifyEdit.Top);
            txt_ModifyEdit.LostFocus += Txt_ModifyEdit_LostFocus;
            txt_ModifyEdit.KeyPress += Txt_ModifyEdit_KeyPress;
        }
        private void LoadProgramEditInterface()
        {
            string[] groupid=DBOperate.GetDesignGroupUsed();
            if (groupid == null || groupid.Length <= 0) return;
            DataTable dtGroup=DBOperate.GetDesignGroupSet();
            if (dtGroup == null || dtGroup.Rows.Count <= 0) return;

            Dictionary<string,int> zonesInPnl=new Dictionary<string, int>();
            int top=lbl_ProgramTitle.Top+lbl_ProgramTitle.Height +5;

            int GroupRows=0;
            Panel pnl=null;
            DataTable dt=DBOperate.GetSetPointSet();
            if (dt == null || dt.Rows.Count == 0) return;
            for (int i = 0 ; i < groupid.Length ; i++)
            {
                zonesInPnl.Add(groupid[i] , 0);
                string s_str = string.Format("groupid='{0}'", groupid[i]);
                DataRow[] dr=dt.Select(s_str);
                GroupRows = (dr.Length - 1) / designCols + 1;
                #region 初始化分组,并创建一个当前分组的pancel
                groupPnl.Add(groupid[i] , new Panel()
                {
                    Size = new Size(this.Width , 35 + 60 * GroupRows) ,
                    Location = new Point(0 , (i > 0 ? groupPnl[groupid[i - 1]].Height + groupPnl[groupid[i - 1]].Top + 10 : top)) ,
                    // BackColor=Color.FromArgb(255,255,192)
                });
                pnl = groupPnl[groupid[i]];
                string[] s = dtGroup.Select("groupid=" + groupid[i])[0]["groupname"].ToString().Split(';');
                Label l = new Label()
                {
                    Name = $"lblGroup{i}",
                    Text = s[MultipleLanguage.systemLanguageIndex],
                    Size = new Size(300, 22),
                    AutoSize = false,
                    BorderStyle = BorderStyle.FixedSingle,
                    Location = new Point(10, 1),
                    TextAlign = ContentAlignment.MiddleCenter,
                    Font= groupTitleFont[MultipleLanguage.systemLanguageIndex],
                    BackColor = Color.Teal,
                    ForeColor = Color.White,
                };
                MultipleLanguage.formLanguage[this.Name].Add(MultipleLanguage.getLanguageCtrl(
                    l.Name, "Label", "Text", s, "", groupTitleFont));
                pnl.Controls.Add(l);
                //lstlbl.Add(l) ;   
                pnl.Controls.Add(new Label()
                {
                    AutoSize = false ,
                    Size = new Size(this.Width , 2) ,
                    BackColor = Color.Gray ,
                    Location = new Point(0 , 6)
                });
                this.Controls.Add(pnl);
                #endregion
            }
            Label lbl;
            string gID="";
            for (int i = 0 ; i < NetLine.setpoint.Count ; i++)
            {
                gID = NetLine.setpoint[i].GroupID.ToString();
                lbl = new Label()
                {
                    Name=$"lblItem{i}",
                    Text = NetLine.setpoint[i].ZoneName[MultipleLanguage.systemLanguageIndex] + " " + NetLine.setpoint[i].Unit,
                    AutoSize = false,
                    Location = new Point(5 + (zonesInPnl[gID] % designCols) * (w + 5), 32 + 60 * (zonesInPnl[gID] / designCols)),
                    Size = new Size(w, 30),
                    Font = itemTitleFont[MultipleLanguage.systemLanguageIndex],
                    Tag = NetLine.setpoint[i].ZoneName, 
                    TextAlign=ContentAlignment.BottomLeft
                };
                MultipleLanguage.formLanguage[this.Name].Add(MultipleLanguage.getLanguageCtrl(
                    lbl.Name, "Label", "Text", NetLine.setpoint[i].ZoneName, NetLine.setpoint[i].Unit, itemTitleFont));
                //lstlbl.Add(lbl);
                groupPnl[gID].Controls.Add(lbl);
                proEdit.Add(new Label()
                {
                    Location = new Point(lbl.Left , lbl.Top + lbl.Height) ,
                    AutoSize = false ,
                    BorderStyle = BorderStyle.FixedSingle ,
                    Tag = NetLine.setpoint[i] ,
                    BackColor = Color.PaleTurquoise ,
                    ForeColor = Color.FromArgb(64 , 64 , 64) ,
                    Size = new Size(w , 30) ,
                    Font = editBoxFont ,
                    TextAlign = ContentAlignment.MiddleCenter ,
                    Text = "0" ,
                });
                proEdit.Last().DoubleClick += proEdit_DoubleClick;
                groupPnl[gID].Controls.Add(proEdit.Last());
                ProgramLabel.Add(NetLine.setpoint[i].ZoneID.ToString() , proEdit.Last());
                zonesInPnl[gID]++;
            }
        }
        private void SetProductInfoGrid()
        {
            DataTable dt=DBOperate.GetProductInfoTitle();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    gridTitle[$"info{dt.Rows[i]["infoid"]}"] = dt.Rows[i]["infotitle"].ToString().Split(';');
                    grdProduct.Columns.Add(gridTitle.Last().Key, gridTitle.Last().Value[MultipleLanguage.systemLanguageIndex]);
                    MultipleLanguage.formLanguage[this.Name].Add(MultipleLanguage.getLanguageCtrl(
                        "grdProduct", "DataGridView", gridTitle.Last().Key, gridTitle[$"info{dt.Rows[i]["infoid"]}"], "", gridTitleFont
                    ));


                    //grdProduct.Columns.Add("info" + dt.Rows[i]["infoid"].ToString() , dt.Rows[i]["infotitle"].ToString());
                }
                grdProduct.Columns.Add("ProductVersion" , "ProductVersion");
                grdProduct.Columns["ProductVersion"].Visible = false;
            }
        }

        private void LoadBatchInfos()
        {
            grdBatchList.Rows.Clear();
            if (NetLine.Batchs.Count == 0) return;
            grdBatchList.Rows.Add(NetLine.Batchs.Count);
            for (int i = 0 ; i < NetLine.Batchs.Count ; i++)
            {
                grdBatchList.Rows[i].Cells["batchserial"].Value = NetLine.Batchs[i].BatchSerial;
                grdBatchList.Rows[i].Cells["createtime"].Value = NetLine.Batchs[i].CreateTime;
                grdBatchList.Rows[i].Cells["stoptime"].Value = NetLine.Batchs[i].StopTime;
                grdBatchList.Rows[i].Cells["isbatchrunning"].Value = NetLine.Batchs[i].isBatchRunning;
                grdBatchList.Rows[i].Cells["createuser"].Value = NetLine.Batchs[i].CreateUser;
                grdBatchList.Rows[i].Cells["ProductVersion"].Value = NetLine.Batchs[i].ProductVersion;
            }
        }
        private void LoadProductInfos()
        {
            DataTable dt = DBOperate.GetProductInfo();
            grdProduct.Rows.Clear();
            if (dt != null && dt.Rows.Count > 0)
            {
                grdProduct.Rows.Add(dt.Rows.Count);
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    for (int j = 0 ; j < grdProduct.Columns.Count ; j++)
                    {
                        grdProduct.Rows[i].Cells[j].Value = dt.Rows[i][grdProduct.Columns[j].Name];
                    }
                }
            }
        }

        private void Txt_ModifyEdit_KeyPress(object sender , KeyPressEventArgs e)
        {
            TextBox txt=txt_ModifyEdit;
            SetPoint sp=txt.Tag as SetPoint;
            int dp=sp.sv.DP + (sp.sv.DataType.ToUpper() == "TIME" ? 1 : 0);
            e.Handled = fdPublicFunction.CheckInput(dp , txt.Text , e);
        }
        private void Txt_ModifyEdit_LostFocus(object sender , EventArgs e)
        {
            TextBox txt= txt_ModifyEdit;
            SetPoint sp=txt.Tag as SetPoint;
            txt.Text = txt.Text.Trim();
            if (txt.Text == "")
            {
                txt.Text = "0";
                return;
            }
            if (Convert.ToSingle(txt.Text) > sp.sv.Max)
            {
                txt.Text = sp.sv.Max.ToString();
                return;
            }
            if (Convert.ToSingle(txt.Text) < sp.sv.Min)
            {
                txt.Text = sp.sv.Min.ToString();
                return;
            }
            if (sp.sv.DataType.ToUpper() == "TIME")//判断时间输入格式
            {
                int i=txt.Text.IndexOf(".");
                if (i >= 0)
                {
                    string s=txt.Text.Substring(i+1);
                    if (s.Length > 2) s = s.Substring(0 , 2);
                    if (Convert.ToInt32(s) > 59)
                        txt.Text = txt.Text.Substring(0 , i) + ".59";
                    else
                        txt.Text = txt.Text.Substring(0 , i) + "." + s;
                }
            }
        }
        private void proEdit_DoubleClick(object sender , EventArgs e)
        {
            if (!isTmpModify) return;
            if (!isCurrentPara) return;
            Label lbl=sender as Label;
            lblModify = lbl;
            SetPoint sp= lbl.Tag as SetPoint;
            txt_ModifyEdit.Tag = lbl.Tag;
            txt_ModifyEdit.Text = lbl.Text;
            pnl_Modify.Location = new Point(lbl.Left,lbl.Top-30);
            pnl_Modify.Parent = lbl.Parent;
            pnl_Modify.Visible = true;
            pnl_Modify.BringToFront();
            lbl_ModifyTitle.Text = sp.ZoneName[formLanguageIndex];
        }
        private bool LoadProductProgram(string ProductVersion)//使用version，从数据库中读取数据，并展示在infoEdit中，通过SVID来设置infoedit的数据
        {
            DataTable dt= DBOperate.GetProductProgram(ProductVersion);
            if (dt == null || dt.Rows.Count == 0)
            {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[6], "", formLanguageIndex);
                //fdMessage.ShowMsg("当前产品还没有设置工艺参数，请先设置工艺参数！" ,"工艺编辑" , 1 , 0);
                foreach (Label item in proEdit)
                    item.Text = "0";
                return false;
            }
            DataRow dr= dt.Rows[0];
            for (int i = 0 ; i < NetLine.setpoint.Count ; i++)
            {
                ProgramLabel[NetLine.setpoint[i].ZoneID.ToString()].Text = dr[NetLine.setpoint[i].ZoneID.ToString()].ToString();
            }
            btn_TmpModify.Enabled = isCurrentPara = false;
            return true;
        }

        private void ExecuteSetValues()
        {
            List<object> v=new List<object>();
            SetPoint sp=null;
            for (int i = 0 ; i < proEdit.Count ; i++)
            {
                sp = proEdit[i].Tag as SetPoint;
                v.AddRange(sp.sv.GetPLCSetValue(proEdit[i].Text));
            }
            NetLine.hsl_SetPoint.SetValues = v;
            NetLine.hsl_SetPoint.IsNeedSetValue = true;
        }

        public void StopBatch()
        {
            NetLine.Batchs.Last().BatchStop();//停止批次
            if (NetLine.Batchs.Last().DictProcessLoad.Count == 0)
                NetLine.Batchs.Last().EndProcessBatch();
            NetLine.isBatchStart = !NetLine.isBatchStart;
            btn_RunConfirm.Visible = !NetLine.isBatchStart;
            btn_BatchStop.Visible = NetLine.isBatchStart;
            LoadBatchInfos();
        }

        

        private void btn_RunConfirm_Click(object sender , EventArgs e)
        {
            if (!NetLine.isBatchStart)//结束当前批次
            {
                isFormLoading = true;
                LoadProductInfos();
                isFormLoading = false;
                if (grdProduct.Rows.Count > 0)
                {
                    grdProduct.Rows[0].Selected = true;
                    SelectedProductVersion = grdProduct.Rows[0].Cells["ProductVersion"].Value.ToString();
                    btn_BatchConfirm.Enabled = LoadProductProgram(SelectedProductVersion);
                }
                pnl_Product.Visible = true;
                pnl_BatchList.Visible = false;
            }

        }

        private void btn_ModifyConfirm_Click(object sender , EventArgs e)
        {
            if (lblModify != null)
                lblModify.Text = txt_ModifyEdit.Text;
            pnl_Modify.Visible = false;
        }

        private void btn_ShowCurrentPara_Click(object sender , EventArgs e)
        {
            ShowCurrentPara();
        }

        public void ShowCurrentPara()
        {
            NetLine.FillSetPoint();
            for (int i = 0 ; i < proEdit.Count && i<NetLine.setpoint.Count ; i++)
            {
                proEdit[i].Text = NetLine.setpoint[i].sv.VisibleValue.ToString();
            }
            btn_TmpModify.Enabled = isCurrentPara = true;
            SelectedProductVersion = "";
            btn_ShowCurrentPara.Focus();
        }

        private void btn_TmpModify_Click(object sender , EventArgs e)
        {
            isTmpModify = true;
            btn_TmpModify.Visible = false;
            btnModifyConfirm.Visible = true;
            OldSetValues.Clear();
            for (int i = 0; i < proEdit.Count; i++)
            {
                OldSetValues.Append(proEdit[i].Text);
            }
        }
        private void grdProduct_SelectionChanged(object sender , EventArgs e)
        {
            if (isFormLoading) return;
            if (grdProduct.CurrentRow != null)
            {
                SelectedProductVersion = grdProduct.CurrentRow.Cells["ProductVersion"].Value.ToString();
                lbl_ProductTitle.Text = "产品信息" + SelectedProductVersion;
                btn_BatchConfirm.Enabled = LoadProductProgram(SelectedProductVersion);
            }
        }

        private void btn_BatchCancel_Click(object sender , EventArgs e)
        {
            pnl_Product.Visible = false;
            pnl_BatchList.Visible = true;
            ShowCurrentPara();
        }

        private void btn_BatchConfirm_Click(object sender , EventArgs e)
        {
            if (SelectedProductVersion == "")
            {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[22], "", formLanguageIndex);
                //fdMessage.ShowMsg("请选择需要热处理的产品后再创建批次!" , "创建批次" , 1 , 0);
                return;
            }
            NetLine.Batchs.Add(new ProcessBatch()
            {
                CreateTime = DateTime.Now ,
                ProductVersion = SelectedProductVersion ,
                CreateUser = fdUsers.UserName.ToString() ,
                BatchSerial = new StringBuilder(DateTime.Now.ToString("yyyyMMdd-HHmmss")) ,
                isBatchRunning = true
            });
           // NetLine.Batchs.Last().SetProductAlarmSettting();
            if (NetLine.Batchs.Last().SaveNewBatchInfo())
            {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[23], NetLine.Batchs.Last().BatchSerial.ToString(), formLanguageIndex);
                //fdMessage.ShowMsg("序列号为【" + NetLine.Batchs.Last().BatchSerial + "】的新批次已创建!" , "创建批次" , 1 , 0);
                ExecuteSetValues();
            }
            NetLine.isBatchStart = !NetLine.isBatchStart;
            btn_RunConfirm.Visible = !NetLine.isBatchStart;
            btn_BatchStop.Visible = !btn_RunConfirm.Visible;
            pnl_Product.Visible = false;
            pnl_BatchList.Visible = true;
            ShowCurrentPara();
            LoadBatchInfos();
        }

        private void btn_BatchStop_Click(object sender, EventArgs e)
        {
            if (NetLine.isBatchStart && NetLine.Batchs.Count > 0)//结束当前批次
            {
                fdMessage.ShowMsg(MultipleLanguage.messageInfos[21], NetLine.Batchs.Last().BatchSerial.ToString(), formLanguageIndex);
                //fdMessage.ShowMsg("确定要结束序列号为【" + NetLine.Batchs.Last().BatchSerial + "】的批次吗？", "结束批次", 2, 4);
            }
        }

        private void btnModifyConfirm_Click(object sender, EventArgs e)
        {
            isTmpModify = true;
            btn_TmpModify.Visible = true;
            btnModifyConfirm.Visible = false;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < proEdit.Count; i++)
            {
                sb.Append(proEdit[i].Text);
            }
            if (!sb.Equals(OldSetValues))
            {
                ExecuteSetValues();
            }
        }
    }
}
